package dm.ast;

import test.envset.GlobalState;

/**
 * DM的exists表达式
 */
public class DmExistsExpression extends DmBoolExpression{
    DmSubSelect s = null;

    public DmExistsExpression() {
        this.op = new DmBoolOperator();
        this.op.setOperator("EXISTS");
    }

    public void setSubSelect(DmSelect s) {
        this.s = new DmSubSelect(s);
    }

    @Override
    public void setWidt(){
        if(s == null){
            wid_t = 10;
        }else {
            wid_t = 1;
            wid_t += s.getWidt();
        }
    }

    @Override
    public void setDept(){
        if(s == null){
            dep_t = 2;
        }else {
            dep_t = s.getDept();
        }
    }


    @Override
    public String toSql(){
        if(s == null){
            return " " + this.getClass().getSimpleName() + getSqlTarget();
        }else {
            StringBuilder sql = new StringBuilder();
            if(notFlag == true){
                sql.append(" NOT");
            }
            sql.append(op.toSql());
            sql.append(s.toSql());
            return sql.toString();
        }
    }

    @Override
    public void fill(GlobalState globalState){
        if(!isCompleted){
            s.fill(globalState);
            isCompleted = true;
        }
    }

    //处理sql错误
    //-4097 | 单行子查询返回多行
    @Override
    public void fixErr4097(){
        if(s != null){
            DmSelect tmpS = s.s;  //exists表达式本身的子查询在exists层次不会出现-4097的错误，但是需要解决子查询内部的-4097错误
            if(tmpS != null){
                tmpS.fixErr4097();
            }
        }
    }

}
